package com.benzhitech.tcp;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * TCP 服务器
 * 负责启动和管理 TCP 服务
 */
public class TcpServer {

    private static final Logger log = LoggerFactory.getLogger(TcpServer.class);
    
    private final int port;
    private final EventLoopGroup bossGroup;
    private final EventLoopGroup workerGroup;
    private ChannelFuture channelFuture;
    
    /**
     * 创建 TCP 服务器
     * 
     * @param port 监听端口
     */
    public TcpServer(int port) {
        this.port = port;
        // 创建两个线程池
        this.bossGroup = new NioEventLoopGroup(1); // Boss 线程组，用于接受连接
        this.workerGroup = new NioEventLoopGroup(); // Worker 线程组，用于处理连接
    }
    
    /**
     * 启动 TCP 服务器
     */
    public void start() throws Exception {
        try {
            // 创建服务器启动器
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 128) // 连接队列大小
                .childOption(ChannelOption.SO_KEEPALIVE, true) // 启用 TCP 保活机制
                .childOption(ChannelOption.TCP_NODELAY, true) // 禁用 Nagle 算法，减少延迟
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new TcpServerHandler());
                    }
                });
                
            // 绑定端口并启动服务
            log.info("TCP 服务器正在启动，监听端口: {}", port);
            channelFuture = b.bind(port).sync();
            log.info("TCP 服务器启动成功，监听端口: {}", port);
            
            // 注册关闭钩子，确保服务器关闭时资源得到释放
            Runtime.getRuntime().addShutdownHook(new Thread(this::stop));
        } catch (Exception e) {
            log.error("TCP 服务器启动失败", e);
            stop();
            throw e;
        }
    }
    
    /**
     * 等待服务器关闭（阻塞方法）
     */
    public void awaitShutdown() throws InterruptedException {
        if (channelFuture != null) {
            // 等待服务器 Socket 关闭
            channelFuture.channel().closeFuture().sync();
        }
    }
    
    /**
     * 停止 TCP 服务器
     */
    public void stop() {
        log.info("正在关闭 TCP 服务器...");
        
        // 优雅地关闭所有线程池
        if (workerGroup != null) {
            workerGroup.shutdownGracefully();
        }
        if (bossGroup != null) {
            bossGroup.shutdownGracefully();
        }
        
        log.info("TCP 服务器已关闭");
    }
    
    /**
     * 获取当前活跃连接数
     */
    public int getActiveConnectionCount() {
        return TcpServerHandler.getActiveConnectionCount();
    }
    
    /**
     * 获取所有活跃连接的 ID
     */
    public String[] getActiveConnectionIds() {
        return TcpServerHandler.getActiveConnectionIds();
    }
    
    /**
     * 向指定连接发送消息
     */
    public boolean sendMessage(String connectionId, String message) {
        return TcpServerHandler.sendMessage(connectionId, message);
    }
    
    /**
     * 断开指定连接
     */
    public boolean disconnectConnection(String connectionId) {
        return TcpServerHandler.disconnectConnection(connectionId);
    }
} 